//
//  WQComposeView.swift
//  WeiBo
//
//  Created by 张德华 on 7/28/16.
//  Copyright © 2016 ZhangDeHua. All rights reserved.
//

import UIKit
import pop
class WQComposeView: UIView {
    
    /**记录mainVc*/
    var target: UIViewController?
    
    /**保存compose模型的数组*/
    lazy var composeButtonInfos: [WQComposeButtonInfo] = [WQComposeButtonInfo]()
    
    /**保存按钮数组*/
    lazy var buttons: [WQComposeButton] = [WQComposeButton]()
    
    // MARK: - ************添加当前view到TabBar上
    func composeViewShow(target: UIViewController) {
        print("composeView")
        
        self.target = target
        
        target.view.addSubview(self)
        
        setupButtonAnim(true)
    }
    
    // MARK: - ************init
    override init(frame: CGRect) {
        super.init(frame: CGRect(x: 0, y: 0, width: SCREENSIZE.width, height: SCREENSIZE.height))
        
        backgroundColor = UIColor.whiteColor()
        
        print("init")
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    
    
    // MARK: - ************设置UI
    func setupUI() {
        
        print("setupUI")
        
        ///------ 添加控件
        addSubview(bgImageView)
        addSubview(logoImageView)
        
        ///------ 控件约束
        bgImageView.snp_makeConstraints { (make) in
            make.edges.equalTo(self).offset(UIEdgeInsetsZero)
        }
        logoImageView.snp_makeConstraints { (make) in
            make.top.equalTo(self).offset(100)
            make.centerX.equalTo(self)
        }
        
        addChildButtons()
    }
    
    
    // MARK: - ************监听方法
    func buttonClicked(button: WQComposeButton) {
        
        // MARK: - 设置按钮动画
        UIView.animateWithDuration(0.25, animations: {
            
            ///------ 遍历保存按钮的数组
            for value in self.buttons {
                
                value.alpha = 0.2
                
                if value == button {
                    ///------ 是当前按钮, 放大
                    value.transform = CGAffineTransformMakeScale(2, 2)
                } else {
                    ///------ 不是当前按钮, 缩小
                    value.transform = CGAffineTransformMakeScale(0.2, 0.2)
                }
            }
            
        }) { (_) in
            
            UIView.animateWithDuration(0.25, animations: { 
                
                for value in self.buttons {
                    
                    ///------ 还原按钮状态
                    value.alpha = 1
                    value.transform = CGAffineTransformIdentity
                }
                
            }, completion: { (_) in
                
                ///------ 判断当前按钮对应的控制器
                guard let vcName = button.composeButtonInfo?.nextvc else {
                    return
                }
                
                guard let pn = NSBundle.mainBundle().infoDictionary!["CFBundleExecutable"] as? String else {
                    return
                }
                
                guard let cn = NSClassFromString("\(pn).\(vcName)") as? UIViewController.Type else  {
                    return
                }
                
                ///------ 初始化
                let tempVc = cn.init()
                let navVc = UINavigationController(rootViewController: tempVc)
                self.target?.presentViewController(navVc, animated: true, completion: { 
                    self.removeFromSuperview()
                })
            })
        }
    }
    
    
    // MARK: - ************创建子控件button
    func addChildButtons() {
        
        ///------ 拿到按钮模型数组
        composeButtonInfos = getComposeButtonInfos()
        
        let column = 3
        
        let btnW: CGFloat = 80
        let btnH: CGFloat = 100
        
        let btnMargin: CGFloat = (SCREENSIZE.width - btnW * 3) / 4
        
        for (i, value) in composeButtonInfos.enumerate() {
            
            let rowIndex = CGFloat(i / column)
            let colIndex = CGFloat(i % column)
            
            let btnX = btnMargin + (btnMargin + btnW) * colIndex
            let btnY = (btnMargin + btnH) * rowIndex + SCREENSIZE.height
            
            ///------ 创建button
            let button = WQComposeButton()
            
            ///------ button属性赋值
            button.composeButtonInfo = value
            
            ///------ 添加监听事件
            button.addTarget(self, action: #selector(WQComposeView.buttonClicked(_:)), forControlEvents: UIControlEvents.TouchUpInside)
            
            button.setImage(UIImage(named: value.icon ?? ""), forState: UIControlState.Normal)
            button.setTitle(value.title, forState: UIControlState.Normal)
            
            button.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
            
            addSubview(button)
            
            ///------ 保存按钮
            buttons.append(button)
        }
        
        
        
    }
    
    
    
    // MARK: - ************读取plist文件, 获取按钮数据(字典转模型)
    func getComposeButtonInfos() -> [WQComposeButtonInfo] {
        
        ///------ 获取路径
        let path = NSBundle.mainBundle().pathForResource("compose.plist", ofType: nil)!
        ///------ plist转为数组
        let array = NSArray(contentsOfFile: path)!
        ///------ 创建临时可变数组
        var tempArray: [WQComposeButtonInfo] = [WQComposeButtonInfo]()
        ///------ 遍历array 字典转模型
        for dict in array {
            let composeButtonInfo = WQComposeButtonInfo(dict: (dict as! [String: AnyObject]))
            tempArray.append(composeButtonInfo)
        }
        return tempArray
    }
    
    
    
    // MARK: - ************屏幕点击
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        
        setupButtonAnim(false)
        
        // TODO: - 延迟移除当前view
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(0.4 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()){
            () in
            self.removeFromSuperview()
        }
        
    }
    
    
    // MARK: - ************设置buttons动画 true: 向上, false: 向下
    func setupButtonAnim(isUp: Bool) {
        
        ///------ 按钮移动的距离
        let margin: CGFloat = isUp ? -350 : 350
        
        ///------ 数组集合
        let set = isUp ? buttons.enumerate() : buttons.reverse().enumerate()
        
        ///------ 遍历按钮数组, 分别设置动画
        for (i, value) in set {
            ///------ 设置动画
            let anim = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            ///------ 设置tovalue
            anim.toValue = NSValue(CGPoint: CGPoint(x: value.center.x, y: value.center.y + margin))
                ///------ 开始时间
                anim.beginTime = CACurrentMediaTime() + Double(i) * 0.025
                ///------ 弹性系数
                anim.springBounciness = 10
                ///------ 动画速度
                anim.springSpeed = 8
                
                value.pop_addAnimation(anim, forKey: nil)
        }
    }
    
    
    
    // MARK: - ************懒加载
    ///------ 背景磨砂图片
    lazy var bgImageView: UIImageView = UIImageView(image: UIImage.getScreenShot().applyLightEffect())
    ///------ logo图片
    lazy var logoImageView: UIImageView = UIImageView(image: UIImage(named: "compose_slogan"))
    
}
